var _startX = 0;            // mouse starting positions
var _startY = 0;
var _offsetX = 0;           // current element offset
var _offsetY = 0;
var _dragElement;           // needs to be passed from OnMouseDown to OnMouseMove
var _oldZIndex = 0;         // we temporarily increase the z-index during drag

function buildGameBoard() {
	var board = document.getElementById("gameboard");

	// place rooms
	for ( var row = 0; row < 800; row = row + 300) {
		for ( var col = 0; col < 800; col = col + 300) {
			placeRoom(row, col, "room", board);
		}
	}

	// place hallways between horizontally aligned rooms
	for ( var row = 50; row < 800; row = row + 300) {
		for ( var col = 200; col < 800; col = col + 300) {
			placeRoom(row, col, "hallway", board);
		}
	}

	// place hallways between vertically aligned rooms
	for ( var row = 200; row < 800; row = row + 300) {
		for ( var col = 50; col < 800; col = col + 300) {
			placeRoom(row, col, "hallway", board);
		}
	}

	// place passages
	for ( var row = 150; row < 800; row = row + 450) {
		for ( var col = 150; col < 800; col = col + 450) {
			placeRoom(row, col, "color-primer", board);
			placeRoom(row, col, "passage", board);
		}
	}
	
	// place playerss
	placePlayers();
	
	// place weapons
	placeWeapons();
	
	// create message area
	var messageBox = document.createElement("div");
	messageBox.style.width=200;
	messageBox.style.height=800;
	messageBox.style.top=0;
	messageBox.style.right=-225;
	messageBox.style.position="absolute";
	var textArea = document.createElement("textarea");
	textArea.id="textArea";
	textArea.style.width="100%";
	textArea.style.height="100%";
	textArea.readOnly=true;
// TODO bind function to onchange event to auto scroll the textarea to the bottom of the text
	messageBox.appendChild(textArea);
	board.appendChild(messageBox);
}

function placeRoom(row, col, type, board) {
	var room = document.createElement("div");
	room.className=type;
	room.style.top = row;
	room.style.left = col;
	board.appendChild(room);
}

function placePlayers() {
	for ( var top=0,left=-125,counter=0;counter<6;counter++,top+=125) {
		var player = document.createElement("div");
		player.className="player";
		player.innerHTML="A Player Marker";
		player.style.top = top;
		player.style.left = left;
		document.getElementById("gameboard").appendChild(player);
	}
}

function placeWeapons() {
	for ( var top=25,left=-100,counter=0;counter<6;counter++,top+=125) {
		var weapon = document.createElement("div");
		weapon.className="weapon";
		weapon.innerHTML="A Weapon Marker";
		weapon.style.top = top;
		weapon.style.left = left;
		document.getElementById("gameboard").appendChild(weapon);
	}
}

function InitDragDrop()
{
    document.onmousedown = OnMouseDown;
    document.onmouseup = OnMouseUp;
}

function OnMouseDown(e)
{
    // IE is retarded and doesn't pass the event object
    if (e == null) 
        e = window.event; 
    
    // IE uses srcElement, others use target
    var target = e.target != null ? e.target : e.srcElement;

    // for IE, left click == 1
    // for Firefox, left click == 0
    if ((e.button == 1 && window.event != null || 
        e.button == 0) && 
        (target.className == 'player' || target.className=='weapon'))
    {
        // grab the mouse position
        _startX = e.clientX;
        _startY = e.clientY;
        
        // grab the clicked element's position
        _offsetX = ExtractNumber(target.style.left);
        _offsetY = ExtractNumber(target.style.top);
        
        // bring the clicked element to the front while it is being dragged
        _oldZIndex = target.style.zIndex;
        target.style.zIndex = 10000;
        
        // we need to access the element in OnMouseMove
        _dragElement = target;

        // tell our code to start moving the element with the mouse
        document.onmousemove = OnMouseMove;
        
        // cancel out any text selections
        document.body.focus();

        // prevent text selection in IE
        document.onselectstart = function () { return false; };
        // prevent IE from trying to drag an image
        target.ondragstart = function() { return false; };
        
        // prevent text selection (except IE)
        return false;
    }
    return true;
}

function OnMouseMove(e)
{
    if (e == null) 
        e = window.event; 

    // this is the actual "drag code"
    _dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px';
    _dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px';  
}

function OnMouseUp(e)
{
    if (_dragElement != null)
    {
        _dragElement.style.zIndex = _oldZIndex;

        // we're done with these events until the next OnMouseDown
        document.onmousemove = null;
        document.onselectstart = null;
        _dragElement.ondragstart = null;
        sendMarkerPosition(_dragElement);
        // TODO parse the return value from the server to see where to place the marker.
        // In the meantime, maybe return the marker to where it started or hide it.
        // the following line should be moved to the callback function when the above is implemented to help keep things in sync
        _dragElement = null;
    }
}

function ExtractNumber(value)
{
    var n = parseInt(value);
	
    return n == null || isNaN(n) ? 0 : n;
}

function sendMarkerPosition(markerObj) {
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange=function () {
		if(xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			var textArea = document.getElementById("textArea")
			if(textArea.value == null || !(textArea.value.length > 0))
				textArea.value = "> " + xmlhttp.responseText;
			else
				textArea.value=textArea.value + "\n" + "> " + xmlhttp.responseText;
		}
	}
	xmlhttp.open("POST","clue-server.php",true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send("left="+markerObj.style.left+"&top="+markerObj.style.top);
}